package com.haoyeteng.sxbd.core.common.constant.factory;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.haoyeteng.sxbd.config.web.SendByEmailConfig;
import com.haoyeteng.sxbd.core.common.constant.cache.Cache;
import com.haoyeteng.sxbd.core.common.constant.cache.CacheKey;
import com.haoyeteng.sxbd.core.common.constant.state.ManagerStatus;
import com.haoyeteng.sxbd.core.common.constant.state.MenuStatus;
import com.haoyeteng.sxbd.core.log.LogObjectHolder;
import com.haoyeteng.sxbd.core.shiro.ShiroKit;
import com.haoyeteng.sxbd.core.support.StrKit;
import com.haoyeteng.sxbd.core.util.Convert;
import com.haoyeteng.sxbd.core.util.DateUtil;
import com.haoyeteng.sxbd.core.util.SpringContextHolder;
import com.haoyeteng.sxbd.core.util.ToolUtil;
import com.haoyeteng.sxbd.modular.system.dao.MenuMapper;
import com.haoyeteng.sxbd.modular.system.dao.RoleMapper;
import com.haoyeteng.sxbd.modular.business.dao.MsgConfigMapper;
import com.haoyeteng.sxbd.modular.business.dao.MsgContentMapper;
import com.haoyeteng.sxbd.modular.business.dao.UserMapper;
import com.haoyeteng.sxbd.modular.business.model.MsgConfig;
import com.haoyeteng.sxbd.modular.business.model.MsgContent;
import com.haoyeteng.sxbd.modular.business.model.User;
import com.haoyeteng.sxbd.modular.system.dao.AdminMapper;
import com.haoyeteng.sxbd.modular.system.model.Menu;
import com.haoyeteng.sxbd.modular.system.model.Role;
import com.haoyeteng.sxbd.modular.system.model.Admin;

/**
 * 常量的生产工厂
 *
 * @author haoyeteng
 * @date 2017年2月13日 下午10:55:21
 */
@Component
@DependsOn("springContextHolder")
public class ConstantFactory implements IConstantFactory {

    private RoleMapper roleMapper = SpringContextHolder.getBean(RoleMapper.class);
    private AdminMapper adminMapper = SpringContextHolder.getBean(AdminMapper.class);
    private MenuMapper menuMapper = SpringContextHolder.getBean(MenuMapper.class);
    private MsgConfigMapper msgConfigMapper = SpringContextHolder.getBean(MsgConfigMapper.class);
	private UserMapper userMapper = SpringContextHolder.getBean(UserMapper.class);
	private MsgContentMapper msgContentMapper = SpringContextHolder.getBean(MsgContentMapper.class);
    
	public static IConstantFactory me() {
        return SpringContextHolder.getBean("constantFactory");
    }

	@Autowired
	private  SendByEmailConfig sendEmail;
	
	@Value("${spring.mail.username}")
	private String senderName;

    /**
     * 根据用户id获取用户名称
     *
     * @author haoyeteng
     * @Date 2017/5/9 23:41
     */
    /*@Override
    public String getAdminNameById(Integer adminId) {
        Admin admin = adminMapper.selectById(adminId);
        if (admin != null) {
            return admin.getName();
        } else {
            return "--";
        }
    }*/

    /**
     * 根据用户id获取用户账号
     *
     * @author haoyeteng
     * @date 2017年5月16日21:55:371
     */
    @Override
    public String getAdminAccountById(Integer adminId) {
        Admin admin = adminMapper.selectById(adminId);
        if (admin != null) {
            return admin.getAccount();
        } else {
            return "--";
        }
    }


    /**
     * 通过角色id获取角色名称
     */
    @Override
    @Cacheable(value = Cache.CONSTANT, key = "'" + CacheKey.SINGLE_ROLE_NAME + "'+#roleId")
    public String getSingleRoleName(Integer roleId) {
        Role roleObj = roleMapper.selectById(roleId);
        if (ToolUtil.isNotEmpty(roleObj) && ToolUtil.isNotEmpty(roleObj.getName())) {
            return roleObj.getName();
        }
        return "";
    }

    /**
     * 通过角色id获取角色英文名称
     */
    @Override
    @Cacheable(value = Cache.CONSTANT, key = "'" + CacheKey.SINGLE_ROLE_TIP + "'+#roleId")
    public String getSingleRoleTip(Integer roleId) {
        if (0 == roleId) {
            return "--";
        }
        Role roleObj = roleMapper.selectById(roleId);
        if (ToolUtil.isNotEmpty(roleObj) && ToolUtil.isNotEmpty(roleObj.getName())) {
            return roleObj.getTips();
        }
        return "";
    }

    /**
     * 获取菜单的名称们(多个)
     */
    @Override
    public String getMenuNames(String menuIds) {
        Integer[] menus = Convert.toIntArray(menuIds);
        StringBuilder sb = new StringBuilder();
        for (int menu : menus) {
            Menu menuObj = menuMapper.selectById(menu);
            if (ToolUtil.isNotEmpty(menuObj) && ToolUtil.isNotEmpty(menuObj.getName())) {
                sb.append(menuObj.getName()).append(",");
            }
        }
        return StrKit.removeSuffix(sb.toString(), ",");
    }

    /**
     * 获取菜单名称
     */
    @Override
    public String getMenuName(Long menuId) {
        if (ToolUtil.isEmpty(menuId)) {
            return "";
        } else {
            Menu menu = menuMapper.selectById(menuId);
            if (menu == null) {
                return "";
            } else {
                return menu.getName();
            }
        }
    }

    /**
     * 获取菜单名称通过编号
     */
    @Override
    public String getMenuNameByCode(String code) {
        if (ToolUtil.isEmpty(code)) {
            return "";
        } else {
            Menu param = new Menu();
            param.setCode(code);
            Menu menu = menuMapper.selectOne(param);
            if (menu == null) {
                return "";
            } else {
                return menu.getName();
            }
        }
    }


    /**
     * 获取性别名称
     */
    @Override
    public String getSexName(Integer sex) {
    	if(sex == 1) {
    		return "男";
    	}else {
    		return "女";
    	}
    }

    /**
     * 获取用户登录状态
     */
    @Override
    public String getStatusName(Integer status) {
        return ManagerStatus.valueOf(status);
    }

    /**
     * 获取菜单状态
     */
    @Override
    public String getMenuStatusName(Integer status) {
        return MenuStatus.valueOf(status);
    }


    /**
     * 获取被缓存的对象(用户删除业务)
     */
    @Override
    public String getCacheObject(String para) {
        return LogObjectHolder.me().get().toString();
    }

	@Override
	public String getAge(Date birthDate) {
		return String.valueOf(DateUtil.getAge(birthDate));
	}

	/**
     * 通过角色ids获取角色名称
     */
    @Override
    @Cacheable(value = Cache.CONSTANT, key = "'" + CacheKey.ROLES_NAME + "'+#roleIds")
    public String getRoleName(String roleIds) {
        Integer[] roles = Convert.toIntArray(roleIds);
        StringBuilder sb = new StringBuilder();
        for (int role : roles) {
            Role roleObj = roleMapper.selectById(role);
            if (ToolUtil.isNotEmpty(roleObj) && ToolUtil.isNotEmpty(roleObj.getName())) {
                sb.append(roleObj.getName()).append(",");
            }
        }
        return StrKit.removeSuffix(sb.toString(), ",");
    }

     public String getAuthState(Integer authState) {
    	 if(authState==-1) {
    		 return "未认证";
    	 }else if(authState==0) {
    		 return "待审核";
    	 }else if(authState==1) {
    		 return "审核通过";
    	 }else 
    		 return "驳回";
    	 
     }
     
     @Override
 	public Object getApplyStateName(Integer applyState) {
 		if(ToolUtil.isNotEmpty(applyState)) {
 			if(applyState == 0) {
 				return "待处理";
 			}else if(applyState == 1) {
 				return "通过";
 			}else {
 				return "驳回";
 			}
 		}
 		return "未申请";
 	}

 	@Override
 	public Object getBindingStateName(Integer bindingState) {
 		if(ToolUtil.isNotEmpty(bindingState)) {
 			if(bindingState == 0) {
 				return "未绑定";
 			}else {
 				return "已绑定";
 			}
 		}
 		return null;
 	}

 	@Override
 	public Object getPayTimeName(Integer payTime) {
 		if(ToolUtil.isNotEmpty(payTime)) {
 			if(payTime >= 12) {
 				Integer year = payTime/12;
 				Integer month = payTime%12;
 				return year + " 年 " + month + " 月 ";
 			}else {
 				return payTime + " 月";
 			}
 		}
 		return null;
 	}

 	@Override
 	public Object getSurplusTimeName(Integer payTime, Date startTime) {
 		if(ToolUtil.isNotEmpty(payTime) && ToolUtil.isNotEmpty(startTime)) {
 			String startTimeTemp = DateUtil.format(startTime, "yyyy-MM-dd HH:mm:ss");
 			//服务到期日期
 			String endTime = DateUtil.addMonth(startTimeTemp, "yyyy-MM-dd HH:mm:ss", payTime);
 			//服务总天数
 			Long totleDays = DateUtil.getDaySub(startTimeTemp, endTime);
 			//已经使用服务的天数
 			Long useDays = DateUtil.getDaySub(startTimeTemp, DateUtil.getTime());
 			//剩余天数
 			Long surplusDays = totleDays - useDays;
 			return surplusDays + " 天";
 		}
 		return null;
 	}

 	/**
 	 * 获取资质等级(1.甲级;2.乙级;3.丙级;4.丁级)
 	 */
	@Override
	public String getMappingGrade(Integer mappingGrade) {
		if(mappingGrade==1) {
			return "甲级";
		} else if(mappingGrade==2) {
			return "乙级";
		}else if(mappingGrade==3) {
			return "丙级";
		}else {
			return "丁级";
		}
		}

	/**
	 * 获取机构类型(0:测绘资质单位,1政府单位（无资质）,2.仪器公司(无资质),3.高校/科研院所(无资质),4.其他非测绘资质执证企业)
	 * @param organType
	 * @return
	 */
	@Override
	public String getOrganType(Integer organType) {
		if(organType==0) {
			return "测绘资质单位";
		}
		else if(organType==1) {
			return "政府单位(无资质)";
		}
		else if(organType==2) {
			return "仪器公司(无资质)";
		}
		else if(organType==3) {
			return "高校/科研所(无资质)";
			
		}else {
			return "其他非测绘资质执证企业";
		}
		
	}
	
    /**
     * 获取申请类型(0.法定代表人申请;1.经办人申请)
     */
	@Override
	public String getApplyType(Integer applyType) {
		if(applyType==0) {
			return "法定代表人申请";
		}else {
			return "经办人申请";
		}
	}
    
	/**
	 * 获得发票类型
	 */
	@Override
	public String getBillType(Integer billType) {
		return billType==0?"增值税普通发票":"增值税专用发票";
	}

	@Override
	public String getOpererType(Integer opererType) {
		return opererType==0?"纸质发票":"";
	}

	@Override
	public String getBillState(Integer billState) {
		if(billState==0) {
			return "未开具";
		}else if(billState==1||billState==2) {
			return "已开具";
		}
			return "已驳回";
	}

	@Override
	public  String delHTMLStyle(String htmlContent) {
	   //去除<html>的标签
		String txtContent=htmlContent.replaceAll("</?[^>]+>","");
	   //去除字符串中的空格、回车、换行符、制表符
		txtContent=txtContent.replaceAll("<a>\\s*|\t|\r|\n</a>", "");
		return txtContent;
		}

	@Override
	public String getMsgType(Integer msgType) {
		if(msgType == 1) {
			return "用户消息";
		}else if(msgType == 2) {
			return "服务消息";
		}else{
			return "支付消息";
		}
	}
     
	/**
	 * 是否已读
	 */
	@Override
	public String getIfRead(Integer ifRead) {
		 return ifRead==0 ? "未读" : "已读";
	}

	@Override
	public void toSendUserMsg(String configName, String content, Integer userId) {
		MsgConfig msgConfig = msgConfigMapper.selectOne(new MsgConfig(configName));
		//判断是前台还是后台，如果是后台判断角色是否符合条件，如果符合条件判断是发送邮寄或者站内消息
		if(msgConfig.getMsgCategory() == 0) {
			//表示是用户消息
			User user = userMapper.selectById(userId);
			if(msgConfig.getIfEmail() == 1) {
				//发邮件，接收邮箱的是当前登录用户
				String title = msgConfig.getTip() + "消息通知";
				sendEmail.send(senderName, user.getEmail(), title, content);
			}
			if(msgConfig.getIfStation() == 1) {
				//发站内
				MsgContent msgContent = new MsgContent();
				msgContent.setCreateMan(user.getUserId());
				msgContent.setCreateTime(new Date());
				msgContent.setUpdateTime(msgContent.getCreateTime());
				msgContent.setMsgCategory(msgConfig.getMsgCategory());
				msgContent.setMsgType(msgConfig.getMsgType());
				msgContent.setIfRead(0);
				msgContent.setMsgContent(content);
				msgContent.setFlag(1);
				msgContentMapper.insert(msgContent);
			}
		}
		
	}


	@Override
	public void toSendAdminMsg(String configName, String content) {
		MsgConfig msgConfig = msgConfigMapper.selectOne(new MsgConfig(configName));
		//判断是前台还是后台，如果是后台判断角色是否符合条件，如果符合条件判断是发送邮寄或者站内消息
		if(msgConfig.getMsgCategory() == 1) {
			//表示是管理员消息
			String[] roleIds = msgConfig.getRoleIds().split(",");
			List<Admin> adminList = adminMapper.selectList(new EntityWrapper<Admin>());
			for (Admin admin : adminList) {
				if(Arrays.asList(roleIds).contains(admin.getRoleid().toString())) {
					if(msgConfig.getIfEmail() == 1) {
						//发邮件
						String title = msgConfig.getTip() + "消息通知";
						sendEmail.send(senderName, admin.getEmail(), title, content);
					}
					if(msgConfig.getIfStation() == 1) {
						//发站内
						MsgContent msgContent = new MsgContent();
						msgContent.setCreateMan(admin.getId());
						msgContent.setCreateTime(new Date());
						msgContent.setUpdateTime(msgContent.getCreateTime());
						msgContent.setMsgCategory(msgConfig.getMsgCategory());
						msgContent.setMsgType(msgConfig.getMsgType());
						msgContent.setIfRead(0);
						msgContent.setMsgContent(content);
						msgContent.setFlag(1);
						msgContentMapper.insert(msgContent);
					}
				}
			}
		}
		
	}


	@Override
	public int getMsgCount() {
		Integer count = msgContentMapper.selectCount(new EntityWrapper<MsgContent>().eq("if_read", 0).and().eq("create_man", ShiroKit.getAdmin().getId()));
		return count;
	}
	
  }


